﻿using HomagChina.Basic.CCT.Tools;
using HomagGroup.Base.UI;
using HomagGroup.Base.UI.Themes.Resources;
using HomagGroup.Base.UI.Windows;
using S7.Net;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Media;
using static HomagChina.Basic.CCT.PLC.SiemensProvider;

namespace Proxy
{
    public class CommonHandle
    {
        SiemensHandle Handle_Siemens;

        public CommonHandle()
        {
            Handle_Siemens = new SiemensHandle();
        }
        /// <summary>
        /// 根据窗口的Title去关闭对应的窗口
        /// </summary>
        /// <param name="Title">窗口的Title</param>
        /// <returns></returns>
        public bool CloseDiaLog(string Title)
        {
            bool result = false;
            try
            {
                foreach (System.Windows.Window window in Application.Current.Windows)
                {
                    if (window.Title.Equals(Title))
                    {
                        window.Close();
                        return result = true;
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                return result;
            }
        }

        #region 反射实现两个类的对象之间相同属性的值的复制

        /// <summary>
        /// 反射实现两个类的对象之间相同属性的值的复制
        /// 适用于初始化新实体
        /// </summary>
        /// <typeparam name="D">返回的实体</typeparam>
        /// <typeparam name="S">数据源实体</typeparam>
        /// <param name="s">数据源实体</param>
        /// <returns>返回的新实体</returns>
        public D Mapper<D, S>(D d, S s)
        {
            try
            {
                var Types = s.GetType();//获得类型
                var Typed = typeof(D);
                foreach (PropertyInfo sp in Types.GetProperties())//获得类型的属性字段
                {
                    foreach (PropertyInfo dp in Typed.GetProperties())
                    {
                        if (dp.Name == sp.Name && dp.PropertyType == sp.PropertyType && dp.Name != "Error" && dp.Name != "Item")//判断属性名是否相同
                        {
                            //if (dp.Name == "CreationDate")
                            //{
                            //    continue;
                            //}
                            dp.SetValue(d, sp.GetValue(s, null), null);//获得s对象属性的值复制给d对象的属性
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return d;
        }

        #endregion 反射实现两个类的对象之间相同属性的值的复制

        #region 系统信息弹窗

        public void OpenInformationCommand(InformationModel Data)
        {
            var version = new Version(Data.Version == null ? "" : Data.Version);
            var Desc = Data.Describe;
            var Title = Data.Title;
            var licenses = new List<string>(Data.licenses.Split(','));
            var appIcon = Application.Current.TryFindResource(InternalKeys.MessageInformationImage) as DrawingBrush;
            var components = new Dictionary<string, string>
            {
                { "powerTouch", Data.powerTouch},
                { "powerControl", Data.powerControl},
                { "HomagGroup.Base.Ui", Data.HomagGroupBaseUi },
                { "Equipment Number",Data.EquipmentNumber},
                { "Main Operating Interface", Data.MainOperatingInterface },
                { "Server Address", Data.ServerAddress },
                { "DataBase Server" ,Data.DataBaseServer },
                { "Database Name", Data.DataBaseName}
            };
            var dialog = new InfoDialog(Desc, Title, version, 1, appIcon, components, licenses);
            dialog.SetValue(UIAdjustments.DisplayModeProperty, DisplayMode.NonTouch);
            dialog.Owner = UIAdjustments.ActiveWindow;
            dialog.ShowDialog();
        }

        #endregion 系统信息弹窗


        public void SendMes2ChainBuffer(Plc plc, string Reference, string Batch, float? Length)
        {
            PlcInfo plcInfo_015 = new PlcInfo
            {
                //写入条码
                DataPath = "DB10.DBB0",
                DataType = VarType.String
            };
            Handle_Siemens.SetValue(plc, plcInfo_015, Reference);
            //写入Batch
            plcInfo_015.DataPath = "DB10.DBB50";
            plcInfo_015.DataType = VarType.String;
            Handle_Siemens.SetValue(plc, plcInfo_015, Batch);
            //写入板子长
            plcInfo_015.DataPath = "DB10.DBB100";
            plcInfo_015.DataType = VarType.Real;
            Handle_Siemens.SetValue(plc, plcInfo_015, Length);
        }


        public void SendMpr2H330(MprStruct mprStruct)
        {
            var mprName = mprStruct.MprName.ToString().Substring(0, 42) + ".mpr";
            var mprConditioins = Getstr(mprStruct.MprName.Substring(42, 38).ToString(), 4);
            mprConditioins[7] = mprStruct.C;
            mprConditioins[8] = mprStruct.Width;
            mprConditioins[9] = mprStruct.Thickness;
            string msg;
            #region Old code
            /*if (mprStruct.TableMode.Equals("3"))
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.Append("%0011\r\n");
                    stringBuilder.Append("5:Name=");
                    stringBuilder.Append(mprName);
                    stringBuilder.Append(";Table1Mode=");
                    stringBuilder.Append(mprStruct.TableMode);
                    stringBuilder.Append(";Table2Mode=##NONE##\r\n");
                    stringBuilder.Append("V1;V2;V3;V4;V5;V6;V7;C;WIDTH;THICKNESS\r\n");
                    stringBuilder.Append(mprConditioins[0] + ";");
                    stringBuilder.Append(mprConditioins[1] + ";");
                    stringBuilder.Append(mprConditioins[2] + ";");
                    stringBuilder.Append(mprConditioins[3] + ";");
                    stringBuilder.Append(mprConditioins[4] + ";");
                    stringBuilder.Append(mprConditioins[5] + ";");
                    stringBuilder.Append(mprConditioins[6] + ";");
                    stringBuilder.Append(mprConditioins[7] + ";");
                    stringBuilder.Append(mprConditioins[8] + ";");
                    stringBuilder.Append(mprConditioins[9]);
                    msg = stringBuilder.ToString().Trim();
                }
                else
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.Append("%0011\r\n");
                    stringBuilder.Append("5:Name=");
                    stringBuilder.Append(mprName);
                    stringBuilder.Append(";Table1Mode=##NONE##;Table2Mode=");
                    stringBuilder.Append(mprStruct.TableMode + "\r\n");
                    stringBuilder.Append("V1;V2;V3;V4;V5;V6;V7;C;WIDTH;THICKNESS\r\n");
                    stringBuilder.Append(mprConditioins[0] + ";");
                    stringBuilder.Append(mprConditioins[1] + ";");
                    stringBuilder.Append(mprConditioins[2] + ";");
                    stringBuilder.Append(mprConditioins[3] + ";");
                    stringBuilder.Append(mprConditioins[4] + ";");
                    stringBuilder.Append(mprConditioins[5] + ";");
                    stringBuilder.Append(mprConditioins[6] + ";");
                    stringBuilder.Append(mprConditioins[7] + ";");
                    stringBuilder.Append(mprConditioins[8] + ";");
                    stringBuilder.Append(mprConditioins[9]);
                    msg = stringBuilder.ToString().Trim();
                }

                if (mprStruct.MachineNum.Equals("H330_1"))
                {
                    SocketHelper socketHelper = new SocketHelper();
                    var s = socketHelper.Connect("192.168.43.120", 52000);
                    socketHelper.Send(s, msg);
                    socketHelper.Dispose(s);
                }
                else
                {
                    SocketHelper socketHelper = new SocketHelper();
                    var s = socketHelper.Connect("192.168.43.121", 52000);
                    socketHelper.Send(s, msg);
                    socketHelper.Dispose(s);
                }*/
            #endregion

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("%0011\r\n");
            stringBuilder.Append("5:Name=");
            stringBuilder.Append(mprName);

            if (mprStruct.TableMode.Equals("3"))
            {
                stringBuilder.Append(";Table1Mode=");
                stringBuilder.Append(mprStruct.TableMode);
                stringBuilder.Append(";Table2Mode=##NONE##\r\n");
            }
            else
            {
                stringBuilder.Append(";Table1Mode=##NONE##;Table2Mode=");
                stringBuilder.Append(mprStruct.TableMode + "\r\n");
            }

            stringBuilder.Append("V1;V2;V3;V4;V5;V6;V7;C;L;E\r\n");
            stringBuilder.Append(string.Join(";", mprConditioins));
            msg = stringBuilder.ToString().Trim();

            SocketHelper socketHelper = new SocketHelper();
            string ipAddress = mprStruct.MachineNum.Equals("H330_1") ? "192.168.43.120" : "192.168.43.121";
            var s = socketHelper.Connect(ipAddress, 52000);
            socketHelper.Send(s, msg);
            socketHelper.Dispose(s);
        }


        /// <summary>
        /// 按照长度拆分字符串
        /// </summary>
        /// <param name="strs"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public String[] Getstr(string strs, int len)
        {
            double i = strs.Length;
            string[] myarray = new string[int.Parse(Math.Ceiling(i / len).ToString())];
            for (int j = 0; j < myarray.Length; j++)
            {
                len = len <= strs.Length ? len : strs.Length;
                myarray[j] = strs.Substring(0, len);
                strs = strs.Substring(len, strs.Length - len);
            }
            return myarray;
        }
    }
}